﻿using Cl.Entity.BaseEntity;
using Cl.Utils;
using SqlSugar;
using SqlSugar.IOC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using static Npgsql.Replication.PgOutput.Messages.RelationMessage;

namespace Cl.Repository
{
    public class ClRepository<T> : SimpleClient<T> where T : class, IDeleted, new()
    {
        public ClRepository(ISqlSugarClient? context = null) : base(context)
        {
            Context = DbScoped.SugarScope;
        }

        /// <summary>
        /// 开启事务
        /// </summary>
        public void BeginTran()
        {
            AsTenant().BeginTran();
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        public void CommitTran()
        {
            AsTenant().CommitTran();
        }

        /// <summary>
        /// 回滚事务
        /// </summary>
        public void RollbackTran()
        {
            AsTenant().RollbackTran();
        }

        #region  ClCommonAuction
        /// <summary>
        /// 逻辑删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public virtual bool ClLogicDelete(Expression<Func<T, bool>> exp)
        {
            var result = Context.Updateable<T>()
               .SetColumns(it => new T() { DeleteTime = DateTime.Now }, true)//true 支持更新数据过滤器赋值字段一起更新
               .Where(exp).ExecuteCommand() > 0;
            return result;
        }

        /// <summary>
        /// 逻辑删除异步
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public virtual async Task<bool> ClLogicDeleteAsync(Expression<Func<T, bool>> exp)
        {
            var result = await Context.Updateable<T>()
               .SetColumns(it => new T() { DeleteTime = DateTime.Now }, true)//true 支持更新数据过滤器赋值字段一起更新
               .Where(exp).ExecuteCommandAsync();
            return result > 0;
        }
        #endregion
    }
}
